import Settings, { SettingsType } from '@database/models/Settings';
import logger from '@utils/logger';

/**
 * Initialize default system settings
 */
export async function seedSettings(): Promise<void> {
  try {
    // Check if system settings already exist
    const existingSettings = await Settings.findOne({ type: SettingsType.SYSTEM, key: 'config' });

    if (existingSettings) {
      logger.info('System settings already exist, skipping initialization');
      return;
    }

    // Create default system config
    await Settings.create({
      type: SettingsType.SYSTEM,
      key: 'config',
      value: {
        siteName: 'DevOps SmartBot',
        siteUrl: 'http://localhost:3000',
        adminEmail: 'admin@devops.com',
        alertRetentionDays: 90,
        ticketRetentionDays: 365,
        enableAIAnalysis: true,
        enableAutoCreateTicket: true,
        slaEnabled: true,
        slaPolicies: {
          critical: 4,   // 4 hours
          high: 8,       // 8 hours
          medium: 24,    // 24 hours
          low: 48        // 48 hours
        },
        maintenanceMode: false,
        maintenanceMessage: ''
      },
      metadata: {
        description: 'System configuration settings',
        category: 'system',
        updatedBy: 'system'
      }
    });

    // Create default notification channels
    await Settings.create({
      type: SettingsType.SYSTEM,
      key: 'notificationChannels',
      value: [
        {
          type: 'email',
          enabled: true,
          config: {
            smtp: {
              host: process.env.SMTP_HOST || 'smtp.gmail.com',
              port: parseInt(process.env.SMTP_PORT || '587'),
              secure: false,
              auth: {
                user: process.env.SMTP_USER || '',
                pass: process.env.SMTP_PASS || ''
              }
            },
            from: process.env.SMTP_FROM || 'noreply@devops.com'
          }
        },
        {
          type: 'slack',
          enabled: false,
          config: {
            webhookUrl: process.env.SLACK_WEBHOOK_URL || '',
            channel: '#devops-alerts'
          }
        },
        {
          type: 'dingtalk',
          enabled: false,
          config: {
            webhookUrl: process.env.DINGTALK_WEBHOOK_URL || '',
            secret: process.env.DINGTALK_SECRET || ''
          }
        },
        {
          type: 'webhook',
          enabled: false,
          config: {
            url: '',
            method: 'POST',
            headers: {}
          }
        }
      ],
      metadata: {
        description: 'Notification channel configurations',
        category: 'notifications',
        updatedBy: 'system'
      }
    });

    // Create default integration settings
    await Settings.create({
      type: SettingsType.INTEGRATION,
      key: 'prometheus',
      value: {
        url: process.env.PROMETHEUS_URL || 'http://prometheus:9090',
        enabled: true
      },
      metadata: {
        description: 'Prometheus integration settings',
        category: 'monitoring',
        updatedBy: 'system'
      }
    });

    await Settings.create({
      type: SettingsType.INTEGRATION,
      key: 'grafana',
      value: {
        url: process.env.GRAFANA_URL || 'http://grafana:3000',
        enabled: true
      },
      metadata: {
        description: 'Grafana integration settings',
        category: 'monitoring',
        updatedBy: 'system'
      }
    });

    await Settings.create({
      type: SettingsType.INTEGRATION,
      key: 'alertmanager',
      value: {
        url: process.env.ALERTMANAGER_URL || 'http://alertmanager:9093',
        enabled: true
      },
      metadata: {
        description: 'AlertManager integration settings',
        category: 'monitoring',
        updatedBy: 'system'
      }
    });

    await Settings.create({
      type: SettingsType.INTEGRATION,
      key: 'openai',
      value: {
        apiKey: process.env.OPENAI_API_KEY || '',
        model: process.env.OPENAI_MODEL || 'gpt-4',
        enabled: !!process.env.OPENAI_API_KEY
      },
      metadata: {
        description: 'OpenAI integration settings',
        category: 'ai',
        updatedBy: 'system'
      }
    });

    logger.info('✅ Default settings initialized successfully');
  } catch (error) {
    logger.error('Failed to seed settings:', error as Error);
    throw error;
  }
}

/**
 * Create default user preferences for admin user
 */
export async function seedAdminPreferences(userId: string): Promise<void> {
  try {
    const existingPrefs = await Settings.findOne({
      type: SettingsType.USER,
      userId,
      key: 'preferences'
    });

    if (existingPrefs) {
      return;
    }

    await Settings.create({
      type: SettingsType.USER,
      userId,
      key: 'preferences',
      value: {
        theme: 'light',
        language: 'auto',
        timezone: 'UTC',
        dateFormat: 'YYYY-MM-DD',
        timeFormat: '24h',
        notifications: {
          email: true,
          browser: true,
          sound: false
        },
        dashboard: {
          layout: ['overview', 'alerts', 'tickets', 'performance'],
          defaultView: 'overview'
        }
      },
      metadata: {
        description: 'User preferences',
        category: 'user',
        updatedBy: userId
      }
    });

    logger.info('✅ Admin user preferences initialized');
  } catch (error) {
    logger.error('Failed to seed admin preferences:', error as Error);
  }
}
